import { AudioSource ,_decorator } from "cc";
import { ResLoader, resLoader } from "../loader/ResLoader";
import { AudioClip } from "cc";
const {ccclass, property} = _decorator;
@ccclass("AudioMusic")
export class AudioMusic extends AudioSource {
    //背景音乐开关
    public switch:boolean = true;
    //背景音乐播放完成回调
    public onCompleted:Function | null = null;

    private _progerss:number = 0; // 进度
    private _isLoading:boolean = false; // 是否正在加载
    private _nextBundleName:string = null!; // 下一个要加载的音乐名称
    private _nextUrl:string = null!; // 下一个要加载的音乐地址

    public start():void{
        this.node.on(AudioSource.EventType.ENDED,this.onAudioEnded,this)
    }

    //播放音乐完成
    private onAudioEnded():void{
        this.onCompleted && this.onCompleted();
    }

    //获取背景音乐播放进度
    get progerss():number{
        if (this.duration > 0) {
            this._progerss = this.currentTime / this.duration;
        }
        return this._progerss;
    }

    //设置背景音乐播放进度
    set progress(value:number){
        this._progerss = value;
        this.currentTime = value * this.duration;
    }

    public async load(url:string, callback?:Function,bundleName:string = resLoader.defaultBundleName){
        if (this._isLoading) { // 如果正在加载，则不再加载
            this._nextBundleName = bundleName;
            this._nextUrl = url;
            return;
        }
        this._isLoading = true;
        let data:AudioClip = await resLoader.loadAsync(bundleName, url, AudioClip);
        if (data) {
            this._isLoading = false;
            if (this._nextUrl!=null) {
                this.load(this._nextUrl, callback, this._nextBundleName);
                this._nextBundleName = this._nextUrl = null!;
            }else{
                callback && callback(data);
                //如果正在播放，则先停止播放
                if (this.playing) {
                    this.stop();
                }
                //删除正在播放的音乐 
                this.release();
                
                //播放背景音乐
                this.clip = data;
                this.play();
            }
        }

    }

    public release():void{
        if (this.clip) {
            this.stop();
            this.clip.decRef();
            this.clip = null;
        }
    }

}